#!/bin/bash
# scan the doc and docx under current dir and subdir for string specific in interactive CLI.

FOLLOW_LINKS=false
SEARCH_DIR="."
SHOW_HELP=false

# Parse command line arguments
while getopts "fh" opt; do
    case $opt in
        f)
            FOLLOW_LINKS=true
            ;;
        h)
            SHOW_HELP=true
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
    esac
done

# Shift processed options away
shift $((OPTIND - 1))

# Show help if requested
if [ "$SHOW_HELP" = true ]; then
    echo "Usage: $0 [-f] [-h] [directory]"
    echo "  -f          Follow symbolic links"
    echo "  -h          Show this help message"
    echo "  directory   Search in specified directory (default: current directory)"
    exit 0
fi

# Check if directory argument is provided
if [ $# -gt 0 ]; then
    SEARCH_DIR="$1"
fi

# Check if directory exists
if [ ! -d "$SEARCH_DIR" ]; then
    echo "Error: Directory '$SEARCH_DIR' does not exist" >&2
    exit 1
fi

# Set find options based on whether to follow links
if [ "$FOLLOW_LINKS" = true ]; then
    FIND_OPTS="-L"
else
    FIND_OPTS=""
fi

   echo -e "\n
Welcome to scandocs. This will search .doc AND .docx files in '$SEARCH_DIR' for a given string. \n
Type in the text string (end with return) you want to find... \n"
   read response
   echo -e "\nNow searching...\n"
   find $FIND_OPTS "$SEARCH_DIR" -name "*.doc" | 
       while read i; do catdoc "$i" | 
                 grep --color=auto -iH --label="$i" "$response"; done
   find $FIND_OPTS "$SEARCH_DIR" -name "*.docx" | 
       while read i; do docx2txt < "$i" | 
                 grep --color=auto -iH --label="$i" "$response"; done
